package com.google.code.p.localspinner;

import static com.google.code.p.localspinner.StaticMemory.FRAMES;
import static com.google.code.p.localspinner.StaticMemory.TXT_PAINT;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.GestureDetector.OnGestureListener;
import android.widget.TextView;
import android.widget.Toast;

import com.google.code.p.localspinner.WheelView.WheelThread;
import com.google.code.p.localspinner.model.Item;
import com.google.code.p.localspinner.model.ItemList;
import com.google.code.p.localspinner.model.ItemList.Type;

public class LocalSpinner extends Activity
{
    private static final float LEFT = 130f;
    private static final float RIGHT = 190f;
    private static final float TOP = 260f;
    private static final float BOTTOM = 330f;
    
    /** A handle to the thread that's actually running the animation. */
    private WheelThread wheelThread;
  
    /** A handle to the View in which the game is running. */
    private WheelView wheelView;
    private GestureDetector gd = null;
    private SearchHelper searchHelper;
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
      //ignore orientation change
      super.onConfigurationChanged(newConfig);
    }
    
    private void showMessage(String errorString) {
        Toast text = Toast.makeText(this, 
                errorString, Toast.LENGTH_SHORT);
        text.show();
    }
    
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        searchHelper = new SearchHelper(this);
        
        Resources res = getResources();
        // cache handles to our key sprites & other drawables
        StaticMemory.WHEEL = res.getDrawable(R.drawable.wheel);
        StaticMemory.CENTER = res.getDrawable(R.drawable.wheel_center);
        
        
        FRAMES[0] = getResources().getDrawable(R.drawable.wheel_1);
        FRAMES[1] = getResources().getDrawable(R.drawable.wheel_2);
        FRAMES[2] = getResources().getDrawable(R.drawable.wheel_3);
        FRAMES[3] = getResources().getDrawable(R.drawable.wheel_4);
        FRAMES[4] = getResources().getDrawable(R.drawable.wheel_5);
        FRAMES[5] = getResources().getDrawable(R.drawable.wheel_6);
        FRAMES[6] = getResources().getDrawable(R.drawable.wheel_7);
        FRAMES[7] = getResources().getDrawable(R.drawable.wheel_8);
        FRAMES[8] = getResources().getDrawable(R.drawable.wheel_9);
        FRAMES[9] = getResources().getDrawable(R.drawable.wheel_10);
        FRAMES[10] = getResources().getDrawable(R.drawable.wheel_11);
        FRAMES[11] = getResources().getDrawable(R.drawable.wheel_12);
        Bundle extras = getIntent().getExtras();
        final ItemList items = (ItemList)extras.get(SearchHelper.ITEMS);
        
        if(!AppUtils.isBlank(items.getListName())){
          setTitle(items.getListName());
        }
        
        Bitmap bm = Bitmap.createBitmap(300, 316, Config.ARGB_8888);
        Canvas cc = new Canvas(bm);
        
        for(int i =0; i< 12; i++){
            Path p = new Path();
            p.moveTo(150, 158);
            
            double deg = ((i+9)*2*Math.PI)/12;
            double r = ((i+9)%2!=0? 150 : 130);
            double x = Math.cos(deg) * r + 150;
            double y = Math.sin(deg) * r + 158;
            p.lineTo((float)x, (float)y);
            
            cc.drawTextOnPath(items.getItem(i).getTitle(), p, 70, 0, TXT_PAINT);
        }
        StaticMemory.TXT_BITMAP = new BitmapDrawable(bm);

     // tell system to use the layout defined in our XML file
        setContentView(R.layout.wheel);
        
        // get handles to the LunarView from XML, and its LunarThread
        wheelView = (WheelView) findViewById(R.id.wheel);
        wheelThread = wheelView.getThread();

        wheelThread.setItemLists(items);
        // give the LunarView a handle to the TextView used for messages
        wheelView.setTextView((TextView) findViewById(R.id.text), (TextView) findViewById(R.id.sm_text));

        
        gd = new GestureDetector(new OnGestureListener(){

          @Override
          public boolean onDown(MotionEvent e) {
            wheelThread.onDown(e);
            return false;
          }

          @Override
          public boolean onFling(MotionEvent e1, MotionEvent e2,
              float velocityX, float velocityY) {
            return false;
          }

          @Override
          public void onLongPress(MotionEvent e) {
          }

          @Override
          public boolean onScroll(MotionEvent e1, MotionEvent e2,
              float distanceX, float distanceY) {
            wheelThread.onScroll(e1, e2, distanceX, distanceY);
            return false;
          }

          @Override
          public void onShowPress(MotionEvent e) {
            // TODO Auto-generated method stub
            
          }

          @Override
          public boolean onSingleTapUp(MotionEvent e) {
            if(LEFT < e.getX() && RIGHT > e.getX()
                && TOP < e.getY() && BOTTOM > e.getY()){
              Item selected = items.getItem(wheelThread.getSlot());
              if(items.getType() == Type.MOVIE){
                  wheelThread.setRunning(false);
                  searchHelper.gotoTrailerUrl(selected.getTitle());
              }else if(!AppUtils.isBlank(selected.getUrl())){
                wheelThread.setRunning(false);
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(selected.getUrl())));
                LocalSpinner.this.finish();
              }else{
                  showMessage("This item does not have an url.");
              }
              return true;
            }
            
            wheelThread.resetVr();
            return true;
          }
          
        });
    }    
    
    @Override
    public boolean onTrackballEvent(MotionEvent event) {
//        Log.d(LocalSpinner.class.toString(), event.toString());
        wheelThread.onTrackball(event);
        return super.onTrackballEvent(event);
    }
    
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gd.onTouchEvent(event);
        
            return super.onTouchEvent(event);
    }
    /**
     * Invoked when the Activity loses user focus.
     */
    @Override
    protected void onPause() {
        super.onPause();
        wheelThread.setRunning(false);
        finish();
    }
    
    @Override
    protected void onResume() {
      super.onResume();
      wheelThread.setRunning(true);
    }

    @Override
    protected void onDestroy() {
      super.onDestroy();
      wheelThread.setRunning(false);
      finish();
    }
    
    public static final int ID_DIALOG_SEARCHING = 0;

    @Override
    protected Dialog onCreateDialog(int id) {
        if(id == ID_DIALOG_SEARCHING){
            ProgressDialog loadingDialog = new ProgressDialog(this);
            loadingDialog.setMessage("Searching...");
            loadingDialog.setIndeterminate(true);
            loadingDialog.setCancelable(true);
            return loadingDialog;
        }

        return super.onCreateDialog(id);
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        try {
            dismissDialog(ID_DIALOG_SEARCHING);
        } catch (Exception e) {
            //ignore error
            Log.e(Search.class.toString(), e.getMessage(), e);
        }
        super.onSaveInstanceState(outState);
    }
}
